<template>
  <div>
    <div class="table-page-search-wrapper">
      <a-row type="flex" justify="space-between" align="middle">
        <a-col :span="16">
          <a-form layout="inline" :model="listQuery">
            <a-form-item label="搜索项">
              <a-input
                v-model:value="listQuery.title"
                placeholder="请输入人员手机号/真实姓名搜索"
              />
            </a-form-item>
            <a-form-item label="状态">
              <a-select v-model:value="listQuery.status" placeholder="请选择">
                <a-select-option key="0" value="0">全部</a-select-option>
                <a-select-option key="1" value="1">正常</a-select-option>
                <a-select-option key="-1" value="-1">禁用</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchSubmit"> 搜索 </a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="8">
          <div style="margin-right: 0px; float: right; display: flex; align-item: center">
            <a-tooltip placement="top">
              <template #title>
                <span>刷新列表</span>
              </template>
              <a-button @click="reloadList">
                <template #icon><SyncOutlined /></template>
              </a-button>
            </a-tooltip>
            <a-button
              v-permission="{ action: 'user_add' }"
              type="primary"
              style="margin-left: 12px"
              @click="addNewData"
            >
              <template #icon><PlusOutlined /></template> 新增用户
            </a-button>
          </div>
        </a-col>
      </a-row>
    </div>
    <a-table
      :columns="columns"
      :rowKey="(record) => record.id"
      :dataSource="dataList.data"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #avatar="{ text: record }">
        <a-avatar :src="record" :srcset="record" alt="头像" size="large" />
      </template>
      <template #username="{ text: record }">
        {{ record.username }}
        <a-tooltip v-if="record.self" placement="top">
          <template #title>
            <span>当前登录账户</span>
          </template>
          <a-tag color="cyan">我</a-tag>
        </a-tooltip>
        <a-tooltip v-if="record.is_admin" placement="top">
          <template #title>
            <span>超级管理员</span>
          </template>
          <a-tag color="blue">超</a-tag>
        </a-tooltip>
      </template>
      <template #status="{ text: record }">
        <a-tag v-if="record == 1" color="blue">正常</a-tag>
        <a-tag v-if="record == -1" color="red">禁用</a-tag>
      </template>
      <template #action="{ text: record }">
        <a
          v-if="record.is_admin !== 1"
          v-permission="{ action: 'user_add' }"
          @click="user_edit(record)"
          ><EditOutlined /> 编辑</a
        >
        <a-divider
          v-if="record.is_admin !== 1"
          v-permission="{ action: 'user_ext' }"
          type="vertical"
        />
        <a-dropdown v-if="record.is_admin !== 1">
          <a v-permission="{ action: 'user_ext' }" class="ant-dropdown-link">
            更多 <DownOutlined
          /></a>
          <template #overlay>
            <a-menu>
              <a-menu-item v-permission="{ action: 'user_fbid' }">
                <a @click="user_fbid(record)"> 禁用</a>
              </a-menu-item>
              <a-menu-item v-permission="{ action: 'user_unfbid' }">
                <a @click="user_unfbid(record)"> 解禁</a>
              </a-menu-item>
              <a-menu-item v-permission="{ action: 'user_del' }" style="color: red">
                <a @click="user_delete(record)"><DeleteOutlined /> 删除</a>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
    </a-table>
    <a-modal
      v-model:open="visible"
      :confirmLoading="confirmLoading"
      :title="operateTitle"
      style="top: 20px"
      :width="800"
      okText="提交"
      @ok="handleOk"
      @cancel="reloadList"
    >
      <a-form ref="formRef" :model="modalFormRef">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="用户名"
          has-feedback
          required
          name="username"
          v-bind="validateInfos.username"
        >
          <a-input v-model:value="modalFormRef.username" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="手机号"
          has-feedback
          required
          name="phone"
          v-bind="validateInfos.phone"
        >
          <a-input v-model:value="modalFormRef.phone" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="密码"
          has-feedback
          required
          name="password"
          v-bind="validateInfos.password"
        >
          <a-input-password
            v-model:value="modalFormRef.password"
            placeholder="最短为8位(不修改请保持此项为空)"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="头像" has-feedback>
          <a-upload
            name="file"
            listType="picture-card"
            class="avatar-uploader"
            :showUploadList="false"
            :action="apiUrl + 'api/common/uploadFile'"
            :headers="uploadHeaders"
            :beforeUpload="beforeUpload"
            @change="uploadChange"
          >
            <img v-if="modalFormRef.avatar" :src="modalFormRef.avatar" alt="avatar" />
            <div v-else>
              <loading-outlined v-if="uploadLoading" />
              <plus-outlined v-else />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="真实姓名">
          <a-input v-model:value="modalFormRef.realName" placeholder="请输入真实姓名" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="用户组"
          has-feedback
          required
          name="groupId"
          v-bind="validateInfos.groupId"
        >
          <a-select v-model:value="modalFormRef.groupId" placeholder="请选择用户组" mode="multiple">
            <a-select-option
              v-for="d in groupList"
              :key="d.id"
              :value="d.id"
              :disabled="d.disabled"
            >
              {{ d.title }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="状态"
          has-feedback
          required
          name="status"
          v-bind="validateInfos.status"
        >
          <a-radio-group v-model:value="modalFormRef.status" name="status">
            <a-radio :key="1" :value="1">正常</a-radio>
            <a-radio :key="-1" :value="-1">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { IconFont } from '@/components/iconfont'
import { defineComponent, reactive, toRefs, onMounted, ref, toRaw } from 'vue'
import { Row, Col, Upload, Modal, Avatar, Divider, Form } from 'ant-design-vue'
import {
  SyncOutlined,
  PlusOutlined,
  LoadingOutlined,
  EditOutlined,
  PlusCircleOutlined,
  CopyOutlined,
  DownOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { requestSuccess, requestFailed } from '@/utils/feedback'
import { validatePassword, validatePhone } from '@/utils/validate'
import { postUserInfo, getUserList, forbidItem, delUser } from '@/api/manage'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { storage } from '@/utils/Storage'
import { apiUrl } from '@/utils/common'

export default defineComponent({
  name: 'UserList',
  components: {
    IconFont,
    SyncOutlined,
    DownOutlined,
    LoadingOutlined,
    PlusOutlined,
    EditOutlined,
    PlusCircleOutlined,
    CopyOutlined,
    DeleteOutlined,
    [Row.name]: Row,
    [Col.name]: Col,
    [Upload.name]: Upload,
    [Divider.name]: Divider,
    [Avatar.name]: Avatar
  },
  setup() {
    const formRef = ref()
    const state = reactive({
      loading: true,
      dataList: [],
      groupList: [],
      uploadHeaders: {},
      visible: false,
      uploadLoading: false,
      confirmLoading: false,
      operateTitle: '编辑',
      apiUrl: apiUrl(),
      imageUrl: '',
      imagePath: '',
      listQuery: {
        type: '0',
        status: '0',
        pageNo: 1,
        pageSize: 12,
        title: ''
      },
      pagination: {
        pageSizeOptions: ['10', '20', '30'],
        showSizeChanger: true,
        total: 1,
        showTotal: (total) => `共 ${total} 条数据`,
        pageSize: 10
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      columns: [
        {
          title: '头像',
          dataIndex: 'avatar',
          slots: { customRender: 'avatar' }
        },
        {
          title: '用户名',
          slots: { customRender: 'username' }
        },
        {
          title: '手机号',
          dataIndex: 'phone'
        },
        {
          title: '用户组',
          dataIndex: 'groupName'
        },
        {
          title: '姓名',
          dataIndex: 'realName'
        },
        {
          title: '创建时间',
          dataIndex: 'create_time'
        },
        {
          title: '最后登录时间',
          dataIndex: 'login_time'
        },
        {
          title: '最后登录IP',
          dataIndex: 'login_ip'
        },
        {
          title: '状态',
          dataIndex: 'status',
          slots: { customRender: 'status' }
        },
        {
          title: '操作',
          width: '150px',
          slots: { customRender: 'action' }
        }
      ]
    })
    const modalFormRef = reactive({
      id: '',
      username: '',
      avatar: '',
      operate_type: 'edit',
      phone: '',
      status: '',
      password: '',
      realName: '',
      groupIds: '',
      groupId: []
    })
    const modalRule = reactive({
      id: [
        {
          required: false
        }
      ],
      username: [
        {
          required: true,
          message: '请输入用户名',
          trigger: ['blur', 'change']
        }
      ],
      phone: [
        {
          required: true,
          message: '请输入手机号',
          trigger: ['blur', 'change']
        },
        {
          validator: validatePhone,
          trigger: ['blur', 'change']
        }
      ],
      password: [
        {
          required: true,
          message: '请输入密码',
          trigger: ['blur', 'change']
        },
        {
          validator: validatePassword,
          trigger: ['blur', 'change']
        }
      ],
      groupId: [
        { required: true, message: '请选择用户组', trigger: ['blur', 'change'], type: 'array' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: ['blur', 'change'], type: 'number' }
      ]
    })
    const { resetFields, validate, validateInfos } = Form.useForm(modalFormRef, modalRule)
    onMounted(() => {
      getDataList()
    })

    function handleTableChange(e) {
      state.loading = true
      state.listQuery.pageSize = e.pageSize
      state.listQuery.pageNo = e.current
      getDataList()
    }

    function reloadList() {
      state.loading = true
      state.listQuery.pageNo = 1
      getDataList()
    }

    function searchSubmit() {
      state.loading = true
      getDataList()
    }

    function getDataList() {
      getUserList(state.listQuery).then((res) => {
        state.loading = false
        state.dataList = res
        state.pagination.total = res.totalCount
        state.groupList = res.authList
      })
    }

    function user_edit(itemData) {
      state.operateTitle = '编辑用户'
      modalFormRef.operate_type = 'edit'
      state.visible = true
      resetFields()
      if (itemData !== undefined && itemData) {
        state.imageUrl = itemData.avatar
        for (let item in itemData) {
          if (item !== 'rules') {
            modalFormRef[item] = itemData[item]
          }
        }
        modalFormRef.operate_type = 'edit'
      }
    }
    function addNewData() {
      state.operateTitle = '新增用户'
      modalFormRef.operate_type = 'add'
      state.visible = true
      resetFields()
    }
    function user_fbid(data) {
      Modal.confirm({
        title: '确认禁用此用户?',
        content: '【' + data.username + '】',
        okType: 'danger',
        onOk() {
          forbidItem({ id: data.id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              reloadList()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    function user_unfbid(data) {
      Modal.confirm({
        title: '确认解除禁用?',
        content: '【' + data.username + '】',
        okType: 'danger',
        onOk() {
          forbidItem({ id: data.id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              reloadList()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    function user_delete(data) {
      Modal.confirm({
        title: '确认永久删除以下用户?',
        content: '【' + data.username + '】',
        okType: 'danger',
        onOk() {
          delUser({ id: data.id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              reloadList()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    function handleOk() {
      validate()
        .then(() => {
          let formRaw = toRaw(modalFormRef)
          state.confirmLoading = true
          formRaw.groupIds = formRaw.groupId.join(',')
          if (modalFormRef.operate_type === 'edit') {
            postUserInfo(formRaw).then((res) => {
              state.confirmLoading = false
              if (res.code === 200) {
                state.visible = false
                reloadList()
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
          } else if (modalFormRef.operate_type === 'add') {
            postUserInfo(formRaw).then((res) => {
              state.confirmLoading = false
              if (res.code === 200) {
                state.visible = false
                requestSuccess(res)
                reloadList()
              } else {
                requestFailed(res)
              }
            })
          }
        })
        .catch(() => {
          return false
        })
    }
    function uploadChange(info) {
      if (info.file.status === 'uploading') {
        state.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        state.imageUrl = info.file.response.url
        state.imagePath = info.file.response.path
        state.uploadLoading = false
      }
    }
    function beforeUpload(file) {
      const token = storage.get(ACCESS_TOKEN)
      if (token) {
        state.uploadHeaders['Authorization'] = 'Bearer ' + token + ':' + new Date().getTime() // 让每个请求携带token
      }
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJPG) {
        requestFailed(null, '仅可上传JPG、PNG格式的文件')
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!isLt2M) {
        requestFailed(null, '上传图片需小于2MB')
      }
      return isJPG && isLt2M
    }
    return {
      ...toRefs(state),
      handleTableChange,
      reloadList,
      beforeUpload,
      uploadChange,
      searchSubmit,
      user_delete,
      formRef,
      modalRule,
      addNewData,
      user_edit,
      modalFormRef,
      validateInfos,
      user_unfbid,
      user_fbid,
      handleOk,
      getDataList
    }
  }
})
</script>

<style scoped></style>
